package com.xin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xin.constant.MessageConstant;
import com.xin.entity.Result;
import com.xin.pojo.OrderSetting;
import com.xin.service.OrderSettingService;
import com.xin.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 夜天
 * @Date 2021/12/16 21:40
 * @Version 1.0.0
 * @description： 预约设置
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Reference
    private OrderSettingService orderSettingService;
    // 文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile){
        try {
            // 使用POI工具类解析表格数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            List<OrderSetting> data = new ArrayList<>();
            // 将字符串转换为日期
            for (String[] strings : list) {
                String orderData = strings[0];
                String number = strings[1];
                OrderSetting orderSetting = new OrderSetting(new Date(orderData),Integer.parseInt(number));
                data.add(orderSetting);
            }
            // 通过 dubbo 远程服务调用连接数据库添加数据
            orderSettingService.add(data);
        } catch (IOException e) {
            e.printStackTrace();
            // 导入失败
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        // 批量导入数据成功
        return new Result(true,MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }
    // 根据月份查询对应的预约设置数据
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){
        try{
            List<Map> list = orderSettingService.getOrderSettingByMonth(date);
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }
    // 根据指定日期修改可预约人数
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try{
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
